package cn.edu.njuit.webserver.securityserver.orders;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Random;

/**
 * @Description: 订单异步制作服务
 * @Data: 2022/9/19 18:49
 * @Author: guzy
 */
@Service
public class MakingService {
    private final OrderRepository orderRepository;
    private final OrderQueueService orderQueueService;
    private Log logger= LogFactory.getLog("订单异步制作服务");
    public MakingService(OrderRepository orderRepository, OrderQueueService orderQueueService) {
        this.orderRepository = orderRepository;
        this.orderQueueService = orderQueueService;
    }
    /**
     * 制作订单：处理订单，处理完成后将指定的订单设置为待配送状态
     * @param orderCode 订单号
     * @return
     */
    @Async
    public OrderEntity processOrder(String orderCode) {
        OrderEntity orderEntity=this.orderRepository.findByOrderCode(orderCode);
        if(orderEntity!=null){
            this.logger.info(String.format("订单开始制作：%s",orderCode));
            Random r=new Random();
            Integer delay=10+r.nextInt(30);
            //模拟订单制作过程，设置10~40秒随机时间等待
            try {
                Thread.sleep(delay*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //订单制作完成标注为待配送状态
            orderEntity.setOrderStatus(OrderStatus.WAITINGRIDER.getName());
            orderEntity.setOrderMadeTime(LocalDateTime.now());
            orderEntity=this.orderRepository.save(orderEntity);
            this.logger.info(String.format("订单制作完成，进入配送状态： %s",orderCode));
            //生产完成发送待配送消息入队列2
            this.orderQueueService.sendOrderDeliveMessage(orderEntity.getOrderCode());
            return orderEntity;
        }
        return null;
    }
}

